/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.jeff.springWebTestNG.service;

import com.jeff.springWebTestNG.TracingService;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingDeque;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

/**
 *
 * @author zhou.zhefu
 */
@TracingService
public class AsyncTimerDemoService implements IAsyncTimerDemoService {
    private Timer timer;
    private BlockingQueue queue = new LinkedBlockingDeque();

    private static long delay = 1000L;
    private static long period = 2000L;

    @PostConstruct
    private void init() {
        timer = new Timer();
        timer.scheduleAtFixedRate(new DemoTimerTask(), delay, period);
    }

    @PreDestroy
    private void terminateTimer() {
        timer.cancel();
    }

    @Override
    public void addThingsToPrint(Object o) {
        queue.offer(o);
    }

    private class DemoTimerTask extends TimerTask {

        @Override
        public void run() {
            //get object from queue, then print them out respectively
            List<Object> queuedThings = new ArrayList<Object>();
            queue.drainTo(queuedThings);

            print(queuedThings);
        }

    }

    private void print(Object o) {
        System.out.println(o.toString());
    }

    private void print(List<Object> list) {
        print("Start printing array...");
        StringBuilder result = new StringBuilder();

        result.append("[");
        for (Object o : list) {
            result.append(o.toString()).append(", ");
        }
        result.append("]");
        print(result);
    }

}
